package xyz.thoughtset.viewer.executor.core.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import xyz.thoughtset.viewer.common.crud.core.service.BaseServiceImpl;
import xyz.thoughtset.viewer.executor.core.dao.QueryBodyDao;
import xyz.thoughtset.viewer.executor.core.dao.QueryParamDao;
import xyz.thoughtset.viewer.executor.core.entity.QueryBody;
import xyz.thoughtset.viewer.executor.core.entity.QueryParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.io.Serializable;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class QueryBodyServiceImpl extends BaseServiceImpl<QueryBodyDao, QueryBody> implements QueryBodyService {

    @Autowired
    private QueryParamDao queryParamDao;


    @Override
    @Transactional
    public Object saveData(LinkedHashMap<String, Object> baseMap) {
        QueryBody entity = (QueryBody) super.saveData(baseMap);
        QueryWrapper<QueryParam> paramQuery = new QueryWrapper();
        paramQuery.lambda().eq(QueryParam::getPid,entity.getId())
                .select(QueryParam::getId);
        List<QueryParam> oldParams = queryParamDao.selectList(paramQuery);
        HashSet params = new HashSet<>();
        for (QueryParam param : entity.getParams()){
            param.setPid(entity.getId());
            queryParamDao.insertOrUpdate(param);
            params.add(param.getId());
        }
        if (!ObjectUtils.isEmpty(oldParams)){
            List<String> delIds = oldParams.stream()
                    .filter(e->!params.contains(e.getId()))
                    .map(QueryParam::getId)  // 提取name属性
                    .collect(Collectors.toList());
            queryParamDao.deleteByIds(delIds);
        }
        return entity;
    }

    @Override
    public boolean deleteById(String pkey) {
        QueryWrapper<QueryParam> query = new QueryWrapper();
        query.lambda().eq(QueryParam::getPid,pkey);
        queryParamDao.delete(query);
        return super.deleteById(pkey);
    }

    @Override
    public QueryBody getById(Serializable id) {
        QueryBody result = super.getById(id);
        QueryWrapper<QueryParam> query = new QueryWrapper();
        query.lambda().eq(QueryParam::getPid,id);
        query.orderByDesc("id");
        result.setParams(queryParamDao.selectList(query));
        return result;
    }


}
